<?php
namespace app\index\model;

use think\Model;

class UserModel extends Model
{
    public static function getUserData($playerId)
    {
        if(empty($playerId))
        {
            return array();
        }
        $playerData = self::where('wx_pid',$playerId)->value('data');
        if(empty($playerData))
        {
            $nickName = request()->param('nickName');
            $sex = request()->param('sex');
            $avatarUrl = request()->param('avatarUrl');

            // create a new player;
            $playerData = array(
                'nickName' => $nickName,
                'sex' => $sex,
                'avatarUrl' => $avatarUrl,
                'playerId' => $playerId,
            );

            self::create([
                'wx_pid'  =>  $playerId,
                'data' =>  $playerData,
                'wx_data' => $playerData,
                'created' => time(),
                'updateTime' => time(),
            ]);
//            trace("sql insert:".json_encode($playerData), 'sql');
        }
        else
        {
            //TODO: process player data. about time limit coins.
            //TODO: also need to update player data
//            trace("sql insert:".json_encode($playerData), 'sql');
            $playerData = json_decode($playerData, true);
        }
        return $playerData;
    }

    public static function saveUserData($playerId, $playerData)
    {
        if(empty($playerId) || empty($playerData))
        {
            return array();
        }
        $user = UserModel::where('wx_pid',$playerId)->find();
        if(empty($user))
        {
            return array();
        }
        else{
            //save data to db
            //update player update time. save user data.

            $user = UserModel::update([
                'data' =>  $playerData,
                'updateTime' => time(),
            ], ['wx_pid' => $playerId]);
        }
//        trace('check player data in userModel:'.json_encode($playerData));
//        return json_decode($playerData, true);
        return $playerData;
    }
}
